package com.anmong.cloud.cloudgateway.filter;

import com.anmong.cloud.cloudgateway.util.IDUtil;
import com.anmong.cloud.mq.constant.HttpEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class CustomizeRequestHeaderGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        HttpHeaders httpHeaders = req.getHeaders();
        ServerHttpRequest.Builder requestBuilder = req.mutate();
        //设置请求id，方便mq回查请求，更改restfull的url为原始值
        requestBuilder.header(HttpEnum.Header.请求ID.code, IDUtil.getUUID());
        ServerHttpRequest request = requestBuilder.build();
        exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -2;
    }
}